package com.example.micrweb.front.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.common.enums.RCode;
import com.example.common.util.JwtUtil;
import com.example.micrweb.front.view.RespResult;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @description: token拦截器，拦截未登录的或者超时的token
 * @author: uu
 * @data: 2023/7/19 下午 03:13
 * @version: v1.0
 */
public class TokenInterceptor implements HandlerInterceptor {

    private String secret = "";

    public TokenInterceptor(String secret) {
        this.secret = secret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        RespResult result = RespResult.fail();
        boolean requestSending = false;
        try {
            // 如果是OPTIONS，放行
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
                return true;
            }
            // 获取token进行，验证
            String headerToken = request.getHeader("Authorization");

            if (StringUtils.isNotBlank(headerToken)){
                headerToken = headerToken.substring(7);
                // 读取jwt
                JwtUtil jwtUtil = new JwtUtil(secret);
                Claims claims = jwtUtil.readJwt(headerToken);
                // 检查是否过期
                Date expiration = claims.getExpiration();
                if (new Date().before(expiration)){
                    // 读取jwt body
                    Integer jwtUid = claims.get("uid", Integer.class);

                    String headerUid = request.getHeader("uid");
                    if (headerUid.equalsIgnoreCase(String.valueOf(jwtUid))){
                        // token 和发起请求的用户是同一个
                        requestSending = true;
                    }
                }
            }

        } catch (Exception e) {
            requestSending = false;
            e.printStackTrace();
        }
        if (!requestSending){
            result.setRCode(RCode.REQUEST_TOKEN_ERR);
            // 使用HttpServletResponse 输出json
            String s = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(s);
            out.flush();
            out.close();
        }
        return requestSending;
    }
}
